package com.leyou.user.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.pojo.PageResult;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * User: ycs
 * Date: 2020/8/29
 * Time: 11:19
 *
 * @author: ycs
 * Description: 用户注册登录业务层
 */
@Service
@Transactional
public class UserService extends ServiceImpl<UserMapper, User> {
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 判断用户名获取手机号唯一
     *
     * @param data
     * @param type
     * @return
     */
    public Boolean IfPhoneOrUserName(String data, String type) {
        User user = new User();
        //判断数据类型
        switch (type) {
            case "1":
                user.setUsername(data);
                break;
            case "2":
                user.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        Wrapper<User> wrapper = Wrappers.query(user);
        Integer count = userMapper.selectCount(wrapper);
        return count == 0;
    }

    /**
     * 发送短信
     *
     * @param phone
     * @return
     */
    public void sendCode(String phone) {
        String code = RandomStringUtils.randomNumeric(6);
        String key = LyConstants.CODE_KEY_PRE + phone;
        //验证码写入缓存15分钟有效
        redisTemplate.opsForValue().set(key, code, 15, TimeUnit.MINUTES);
        /*发送消息到对列*/
        Map map = new HashMap<String, Object>(2);
        map.put("phone", phone);
        map.put("code", code);
        amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME, MQConstants.RoutingKey.VERIFY_CODE_KEY, map);
    }

    /**
     * 用户注册
     *
     * @param user
     * @param code
     */
    public void userRegister(User user, String code) {
        //从缓存中获取验证码
        String redisCode = redisTemplate.opsForValue().get(LyConstants.CODE_KEY_PRE + user.getPhone());
        //判断验证码
        if (!StringUtils.equals(redisCode, code)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //密码加密
       user.setPassword(passwordEncoder.encode(user.getPassword()));
        //存入数据库
        int count = userMapper.insert(user);
        if (count!=1){
            throw  new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }
    /**
     * 根据用户名与密码查询用户
     * @param username
     * @param password
     * @return
     */
    public User findByUsernameAndPassword(String username, String password) {
        User entity  =new User();
        entity.setUsername(username);
        Wrapper<User> wrapper = Wrappers.query(entity);
        User user = userMapper.selectOne(wrapper);
        //验证用户
        if (user==null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //验证密码
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if (!matches){
            //密码错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return user;
    }
}
